import { login, getProfice, getUserInfoById } from '@/api/user'
import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth'
import { resetRouter } from '@/router'

export default {
  namespaced: true,
  state: {
    // token: localStorage.getItem('token') || ''
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      // 实现持久化
      // localStorage.setItem('token', token)
      setToken(token)
    },
    delToken(state) {
      state.token = ''
      removeToken()
    },
    setUserInfo(state, info) {
      state.userInfo = info
    },
    removeInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    // 退出登录情况token,用户信息
    logout(context) {
      context.commit('delToken')
      context.commit('removeInfo')
      // 重置路由
      resetRouter()
    },
    // 2.获取用户信息存储到vuex中
    async setUserInfo(context) {
      try {
        const res = await getProfice()
        console.log(res)
        const info = await getUserInfoById(res.data.userId)
        console.log(info)
        context.commit('setUserInfo', { ...info.data, ...res.data })
        return res.data.roles.menus
      } catch (error) {
        console.log(error, '获取用户信息失败')
      }
    },
    async userLogin(context, formData) {
      console.log(context)
      // context是store的实例
      const { data } = await login(formData)
      console.log(data)
      context.commit('setToken', data)
      // 调用存储获取token时的时间戳
      setTimeStamp()
    }
  }
}

